<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Produk extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->model('Produk_model');
		$this->load->helper('bantuan_helper');
		$this->load->helper('file');
		$this->load->library('image_lib');
		if(!$this->session->userdata('user_id') && !$this->session->userdata('user_display_name') ):
		redirect('backend');
		endif;
	}

	function index()
	{
		$this->load->library('pagination');
		$offset = $this->uri->segment(4);
		$config['base_url'] = site_url().'/backend/produk/index';
		$config['total_rows'] = count($this->Produk_model->getProduk('all'));
		$config['per_page'] = $this->config->item('per_page');
		$config['uri_segment'] = '4';
		
		$data['urut'] = $this->uri->segment(4);
		$data['title'] = 'Produk';
		$data['template'] = 'produk/index';
		$data['res'] = $this->Produk_model->getProduk('all',FALSE,FALSE,FALSE,$config['per_page'],$offset);
		$this->pagination->initialize($config);
		$this->load->view('backend/index',$data);
	}
	
	
	function search_result()
	{
		$this->form_validation->set_rules('nama_produk', 'Name','required');
		//$this->form_validation->set_rules('prod_kat_id', 'Kategori','required');
		if ($this->form_validation->run() == FALSE)
		{
			redirect('backend/produk');
		}
		else
		{
			$nm_prod = $this->input->post('nama_produk');
			$kat_prod = $this->input->post('prod_kat_id');
		
			$this->load->library('pagination');
			$offset = $this->uri->segment(4);
			$config['base_url'] = site_url().'/backend/produk/search_result';
			$config['total_rows'] = count($this->Produk_model->getcariProduk($nm_prod,$kat_prod,FALSE,FALSE));
			$config['per_page'] = $this->config->item('per_page');
			$config['uri_segment'] = '4';
			
			$data['urut'] = $this->uri->segment(4);
			$data['title'] = 'Produk';
			$data['template'] = 'produk/index';
			$data['res'] = $this->Produk_model->getcariProduk($nm_prod,$kat_prod,$config['per_page'],$offset);
			$this->pagination->initialize($config);
			$this->load->view('backend/index',$data);
		
		}
	}

	function add()
	{
		$this->form_validation->set_rules('nama_produk', 'Name','required');
		$this->form_validation->set_rules('kode_produk', 'Kode Produk','required');
		$this->form_validation->set_rules('deskripsi', 'Deskripsi','required');
		$this->form_validation->set_rules('prod_kat_id', 'Kategori Produk','required');
		$this->form_validation->set_rules('prod_brand_id', 'Vendor','required');
		$this->form_validation->set_rules('harga', 'Harga Distributor','required');
		$this->form_validation->set_rules('tersedia', 'Ketersediaan','required');
		$this->form_validation->set_rules('status', 'Status','required');
		$this->form_validation->set_rules('promo', 'Promo','required');

		if ($this->form_validation->run() == FALSE):
			if ($this->input->post('produk_id')):
				$data['produk_id'] = $this->input->post('produk_id');
			endif;
			$data['title'] = 'Produk';
			$data['template'] = 'produk/add';
			$this->load->view('backend/index',$data);
		else:
			/*
			$prod_data = array(
				'prod_kat_id' => $this->input->post('prod_kat_id'),
				'prod_brand_id' => $this->input->post('prod_brand_id'),
				'nama_produk' => $this->input->post('nama_produk'),
				'kode_produk' => $this->input->post('kode_produk'),
				'deskripsi' => $this->input->post('deskripsi'),
				'deskripsi_promo' => $this->input->post('deskripsi_promo'),
				'harga' => $this->input->post('harga'),
				'persen_diskon' => $this->input->post('persen_diskon'),
				'tersedia' => $this->input->post('tersedia'),
				'status' => $this->input->post('status'),
				'promo' => $this->input->post('promo'),
			);
			if($this->input->post('produk_id')):
				for($i=1;$i<=6;$i++):
					$data = array(
						'produk_id' => $this->input->post('produk_id'),
						'ms_size_id' => $i,
						'jml_item' => $this->input->post('size_'.$i)
					);
					$this->db->insert('tb_size_produk',$data);
				endfor;
				$this->db->where('produk_id',$this->input->post('produk_id'))
					->update('tb_produk',$prod_data);
				redirect('backend/product');
			else:
				for($i=1;$i<=6;$i++):
					$data = array(
						'produk_id' => $this->input->post('produk_id'),
						'ms_size_id' => $i,
						'jml_item' => $this->input->post('size_'.$i)
					);
					$this->db->insert('tb_size_produk',$data);
				endfor;
				$this->db->insert('tb_produk',$prod_data);
				redirect('backend/product');
			endif;*/
			echo '<pre>';
			print_r($_POST);
			echo '</pre>';
		endif;
	}

	function edit($id=FALSE)
	{
		$this->form_validation->set_rules('nama_produk', 'Name','required');
		$this->form_validation->set_rules('kode_produk', 'Kode Produk','required');
		$this->form_validation->set_rules('deskripsi', 'Deskripsi','required');
		$this->form_validation->set_rules('prod_kat_id', 'Kategori Produk','required');
		$this->form_validation->set_rules('prod_brand_id', 'Vendor','required');
		$this->form_validation->set_rules('harga', 'Harga Distributor','required');
		$this->form_validation->set_rules('tersedia', 'Ketersediaan','required');
		$this->form_validation->set_rules('status', 'Status','required');
		$this->form_validation->set_rules('promo', 'Promo','required');

		if ($this->form_validation->run() == FALSE):
			$id = $this->uri->segment(4);
			$data['title'] = 'Product';
			$data['template'] = 'produk/edit';
			$data['produk_id'] = $id;
			$data['row'] = $this->Produk_model->getProductById($id);
			$this->load->view('backend/index',$data);
		else:
			// insert size
			$this->db->where('produk_id', $this->input->post('produk_id'));
			$this->db->delete('tb_size_produk');
			for($i=1;$i<=6;$i++):
				$data = array(
					'produk_id' => $this->input->post('produk_id'),
					'ms_size_id' => $i,
					'jml_item' => $this->input->post('size_'.$i)
				);
				$this->db->insert('tb_size_produk',$data);
			endfor;
			$prod_data = array(
				'prod_kat_id' => $this->input->post('prod_kat_id'),
				'prod_brand_id' => $this->input->post('prod_brand_id'),
				'nama_produk' => $this->input->post('nama_produk'),
				'kode_produk' => $this->input->post('kode_produk'),
				'deskripsi' => $this->input->post('deskripsi'),
				'deskripsi_promo' => $this->input->post('deskripsi_promo'),
				'harga' => $this->input->post('harga'),
				'persen_diskon' => $this->input->post('persen_diskon'),
				'tersedia' => $this->input->post('tersedia'),
				'status' => $this->input->post('status'),
				'promo' => $this->input->post('promo'),
			);
			$this->db->where('produk_id',$this->input->post('produk_id'))->update('tb_produk',$prod_data);
			redirect('backend/produk');
		endif;
	}
	
	function upload_image($produk_id,$look,$submit=FALSE)
	{
		$submit = $this->uri->segment(6);
		if($submit):
			if((!empty($_FILES['image_file']['tmp_name'])) && ($_FILES['image_file']['tmp_name']!="")):
				$this->uploadImage($produk_id,$look);
				// redirect
				$this->session->set_flashdata('message_type','success');
				$this->session->set_flashdata('message', 'Your image has been updated');
				redirect('backend/produk/edit/'.$produk_id);
			else:
				$this->session->set_flashdata('message_type','error');
				$this->session->set_flashdata('message', 'Please choose picture file');
				redirect('backend/produk/edit/'.$produk_id);
			endif;
		else:
			$data['produk_id'] = $produk_id;
			$data['look'] = $look;
			$this->load->view('backend/produk/upload_image',$data);
		endif;
	}
	
	function uploadImage($produk_id,$look)
	{
		$this->load->helper('file');

		$absolutePath = $this->config->item("absolutePathFile").'product/';
		// config untuk upload
		$config['upload_path'] = $this->config->item("upload_path_temp");
		$config['allowed_types'] = 'jpg|jpeg';
		$config['max_size'] = $this->config->item("max_size");
		$config['max_width'] = $this->config->item("max_width");
		$config['max_height'] = $this->config->item("max_height");
		$config['remove_spaces'] = $this->config->item("remove_spaces");

		// inisialisasi library upload
		$this->load->library('upload', $config);
		$large_resize_width = getOption('media_large_width');
		$large_resize_height = getOption('media_large_height');
		$medium_resize_width = getOption('media_medium_width');
		$medium_resize_height = getOption('media_medium_height');
		$thumbnail_size = getOption('media_thumbnail_size');

		// uploading
		if (!$this->upload->do_upload('image_file')):
			print_r($this->upload->display_errors());
		else:
			$uploaded_photo = array('upload_photo' => $this->upload->data());
			$file_uploaded = $uploaded_photo['upload_photo']['file_name'];
			$file_ext = $uploaded_photo['upload_photo']['file_ext'];
			$randName = 'p_'.mt_rand(100000,999999);
			$newName = $randName;
			while(file_exists($config['upload_path'].$newName)):
				$randName = 'p_'.mt_rand(100000,999999);
				$newName = $randName;
			endwhile;
			$fileDate = date("YmdHis");
			$newFileName = $newName.'_'.$fileDate.$file_ext;
			if(!file_exists($config['upload_path'].$newFileName)):
				rename($config['upload_path'].$file_uploaded, $config['upload_path'].$newFileName);
			endif;

			// config untuk resize
			$config['media_path'] = $this->config->item("upload_path").'product/';
			$config['image_library'] = $this->config->item("image_library");
			$config['maintain_ratio'] =$this->config->item("maintain_ratio");
			$config['width'] = getOption('media_large_width');
			$config['height'] = getOption('media_large_height');

			$config['source_image'] = $config['upload_path'].$newFileName;

			require_once FCPATH . APPPATH . 'libraries/phpthumb/ThumbLib.inc.php';
			
			$filename_noext = $newName.'_'.$fileDate;
			$thumb = PhpThumbFactory::create($config['upload_path'].$newFileName);
			$thumb->adaptiveResize($large_resize_width, $large_resize_height);
			$thumb->save($absolutePath . $filename_noext . '_'.$large_resize_width.'x'.$large_resize_height.'.jpg', 'jpg');
			$large_image = $filename_noext . '_'.$large_resize_width.'x'.$large_resize_height.'.jpg';
			
			$thumb = PhpThumbFactory::create($config['upload_path'].$newFileName);
			$thumb->adaptiveResize($medium_resize_width, $medium_resize_height);
			$thumb->save($absolutePath . $filename_noext . '_'.$medium_resize_width.'x'.$medium_resize_height.'.jpg', 'jpg');
			$medium_image = $filename_noext . '_'.$medium_resize_width.'x'.$medium_resize_height.'.jpg';
			
			$thumb = PhpThumbFactory::create($config['upload_path'].$newFileName);
			$thumb->adaptiveResize($thumbnail_size, $thumbnail_size);
			$thumb->save($absolutePath . $filename_noext . '_'.$thumbnail_size.'x'.$thumbnail_size.'.jpg', 'jpg');
			$thumb_image = $filename_noext . '_'.$thumbnail_size.'x'.$thumbnail_size.'.jpg';
			unlink($config['upload_path'].$newFileName);
			$cekData = $this->db->where('produk_id',$produk_id)
						->where('look',$look)
						->get('tb_image_produk')
						->row();
			if(count($cekData)>0):
				if(!empty($cekData->produk_img_url) && file_exists($absolutePath.$cekData->produk_img_url)):
					unlink($absolutePath.$cekData->produk_img_url);
				endif;
				if(!empty($cekData->produk_img_thumb) && file_exists($absolutePath.$cekData->produk_img_thumb)):
					unlink($absolutePath.$cekData->produk_img_thumb);
				endif;
				if(!empty($cekData->produk_img_url_small) && file_exists($absolutePath.$cekData->produk_img_url_small)):
					unlink($absolutePath.$cekData->produk_img_url_small);
				endif;
				$this->db->where('produk_id', $produk_id);
				$this->db->delete('tb_image_produk');
			endif;
			$data = array(
				'produk_id' => $produk_id,
				'produk_img_url' => $large_image,
				'produk_img_url_small' => $medium_image,
				'produk_img_thumb' => $thumb_image,
				'look' => $look
			);
			$this->db->insert('tb_image_produk',$data);
		endif;
	}

	function delete($id)
	{
		$id = $this->uri->segment(4);
		$cekData = $this->db->where('produk_id',$produk_id)
					->where('look',$look)
					->get('tb_image_produk')
					->row();
		if(count($cekData)>0):
			if(!empty($cekData->produk_img_url) && file_exists($absolutePath.$cekData->produk_img_url)):
				unlink($absolutePath.$cekData->produk_img_url);
			endif;
			if(!empty($cekData->produk_img_thumb) && file_exists($absolutePath.$cekData->produk_img_thumb)):
				unlink($absolutePath.$cekData->produk_img_thumb);
			endif;
			if(!empty($cekData->produk_img_url_small) && file_exists($absolutePath.$cekData->produk_img_url_small)):
				unlink($absolutePath.$cekData->produk_img_url_small);
			endif;
			$this->db->where('produk_id', $produk_id);
			$this->db->delete('tb_image_produk');
		endif;
		$this->db->where('produk_id',$id)->delete('tb_size_produk');
		$this->db->where('produk_id',$id)->delete('tb_produk');
		redirect('backend/produk');
	}
	
	function ajax_bulk_action()
	{
		foreach($_POST["produk_id"] as $prod_id):
			$cekData = $this->db->where('produk_id',$prod_id)
				->where('look',$look)
				->get('tb_image_produk')
				->row();
			if(count($cekData)>0):
				if(!empty($cekData->produk_img_url) && file_exists($absolutePath.$cekData->produk_img_url)):
					unlink($absolutePath.$cekData->produk_img_url);
				endif;
				if(!empty($cekData->produk_img_thumb) && file_exists($absolutePath.$cekData->produk_img_thumb)):
					unlink($absolutePath.$cekData->produk_img_thumb);
				endif;
				if(!empty($cekData->produk_img_url_small) && file_exists($absolutePath.$cekData->produk_img_url_small)):
					unlink($absolutePath.$cekData->produk_img_url_small);
				endif;
				$this->db->where('produk_id', $prod_id)->delete('tb_image_produk');
			endif;
			$this->db->where('produk_id',$prod_id)->delete('tb_size_produk');
			$this->db->where('produk_id',$prod_id)->delete('tb_produk');
		endforeach;
	}
	
	function get_kategori($prod_kat_id_default)
	{
		if($_POST):
			$brand_id = $_POST['brand_id'];
			$selected = FALSE;
			if($prod_kat_id_default!='0'):
				$selected = $prod_kat_id_default;
			endif;
			echo produk_category_dropdown($brand_id, '0', $selected);
		endif;
	}
	
	function ajax_save_new_product()
	{
		$data = array(
					'nama_produk'=>strip_tags($_POST['nama_produk']),
					'prod_brand_id'=>strip_tags($_POST['prod_brand_id']),
					'prod_kat_id'=>strip_tags($_POST['prod_kat_id']),
				);

		$this->db->insert('tb_produk',$data);
		$produk_id = $this->db->insert_id();
		for($i=1;$i<=6;$i++):
			$data_size = array(
				'produk_id' => $produk_id,
				'ms_size_id' => $i,
				'jml_item' => $this->input->post('size_'.$i)
			);
			$this->db->insert('tb_size_produk',$data_size);
		endfor;
		
		echo $produk_id;
	}
}

/* End of file product.php */
/* Location: ./system/application/controllers/backend/product.php */
